package com.example.myapplication.BleGATT;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import com.example.myapplication.RunActivity;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@SuppressLint("MissingPermission")

public class ClientUtils {
    private final Context context;
    private final BluetoothAdapter bluetoothAdapter;
    private BluetoothGatt bluetoothGatt;
    private final Intent BleStateIntent = new Intent("BleStateBroadcast");
    private boolean isScanning = false;
    private final RunActivity mActivity;
    private BluetoothDevice mDevice;

    // 服务uuid
    public static  UUID UUID_SERVER = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
    // 读的特征值
    public static  UUID UUID_CHAR_READ = UUID.fromString("0000ffe3-0000-1000-8000-00805f9b34fb");
    // 写的特征值
    public static  UUID UUID_CHAR_WRITE = UUID.fromString("0000ffe4-0000-1000-8000-00805f9b34fb");
    List<BluetoothDevice> scannedDevices = new ArrayList<>();
    private final Handler handler=new Handler();


    public ClientUtils(Context context, RunActivity mAct) {
        this.context = context;
        this.mActivity=mAct;
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

    }
    /**
     * 开始扫描设备
     */
    @SuppressLint("MissingPermission")
    public void startScan() {
        if (bluetoothAdapter == null || isScanning) return;

        BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
        if (scanner != null) {
            scanner.startScan(scanCallback);
            isScanning = true;
        }

        // 开启定时任务，在SCAN_PERIOD时间后停止扫描
        handler.postDelayed(this::stopScan, 2000);
    }
    public void stopScan() {
        if (bluetoothAdapter == null || !isScanning) return;
        BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
        if (scanner != null) {
            scanner.stopScan(scanCallback);
            isScanning = false;
        }
    }
    // 扫描的监听回调
    private final ScanCallback scanCallback = new ScanCallback() {

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();
            if (!scannedDevices.contains(device)) {
                scannedDevices.add(device);
               mActivity.setBluetoothDevice(scannedDevices);

            }
        }

    };

    /**
     * 连接指定设备
     *
     * @param device
     */

    public void connectDevice(BluetoothDevice device) {
        mDevice=device;
        bluetoothGatt = mDevice.connectGatt(context, false, bluetoothGattCallback);
    }

    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                // 请求较大的 MTU 大小
                int desiredMtu = 512; // 你希望的 MTU 大小
                bluetoothGatt.requestMtu(desiredMtu);
                Log.e("TAG", "onConnectionStateChange 连接成功");
                //修改状态为客户端
                gatt.discoverServices();
                mActivity.setisServer(false);
                // 创建意图对象
                BleStateIntent.putExtra("message", "200");
                // 发送广播
                mActivity.sendBroadcast(BleStateIntent);
                //再次连接

            } else if (newState == BluetoothGatt.STATE_CONNECTING) {
                Log.e("TAG", "onConnectionStateChange 连接中......");
                BleStateIntent.putExtra("message", "100");
                // 发送广播
                mActivity.sendBroadcast(BleStateIntent);
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                Log.e("TAG", "onConnectionStateChange 连接断开");
                BleStateIntent.putExtra("message", "400");
                // 发送广播
                mActivity.sendBroadcast(BleStateIntent);
                mActivity.setisServer(true);
            } else if (newState == BluetoothGatt.STATE_DISCONNECTING) {
                Log.e("TAG", "onConnectionStateChange 连接断开中......");
                BleStateIntent.putExtra("message", "500");
                // 发送广播
                mActivity.sendBroadcast(BleStateIntent);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            // 设置读特征值的监听，接收服务端发送的数据
            // 获取服务和特征值
            // 发起读取请求
            BluetoothGattService service = bluetoothGatt.getService(UUID_SERVER);
            BluetoothGattCharacteristic characteristicRead = service.getCharacteristic(UUID_CHAR_READ);
            @SuppressLint("MissingPermission")
            boolean b = bluetoothGatt.setCharacteristicNotification(characteristicRead, true);
            Log.e("TAG", "onServicesDiscovered 设置通知 " + b);
            mActivity.setisServer(false);

        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            byte[] data = characteristic.getValue();
            Log.d("TAG","客户端感应到了服务端属性值被修改！！！");
            // 在这里进行进一步的处理，如解析数据、执行操作等
            String dataStr = new String(data, StandardCharsets.UTF_8);
            Log.d("TAG", "完整数据: " + dataStr);
            // 将数据发送给其他组件，通过广播或回调等方式
            Intent intent = new Intent("com.example.ACTION_DATA_RECEIVED");
            intent.putExtra("ReceivedData", dataStr);
            context.sendBroadcast(intent);

        }

    };
    /**
     * 发送数据
     *
     * @param msg 要发送的数据
     */
    @SuppressLint("MissingPermission")
    public void sendData(String msg) {
        // 找到服务
        BluetoothGattService service = bluetoothGatt.getService(UUID_SERVER);
        if(service!=null){
            // 拿到写的特征值
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID_CHAR_WRITE);
            bluetoothGatt.setCharacteristicNotification(characteristic, true);

            byte[] dataBytes = msg.getBytes(StandardCharsets.UTF_8);
                characteristic.setValue(dataBytes);
                bluetoothGatt.writeCharacteristic(characteristic);
            Log.e("TAG", "sendData 发送数据成功");
        }
        else {
            Log.e("TAG", "sendData 发送数据失败");
        }

    }

    public boolean isBluetoothConnected() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
    }

}
